package com.csq.service.impl;

import com.csq.entity.Account;
import com.csq.mapper.AccountMapper;
import com.csq.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author ercai
 * @date 2019/7/26 - 16:25
 */
@Service
@Transactional(isolation= Isolation.READ_UNCOMMITTED)
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    //注入事务管理模板
    /*private TransactionTemplate transactionTemplate;

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }*/

    /*public boolean tranfer(final int one, final int two, final BigDecimal money) {
        this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {

                //1.判断钱够不够
                Account account1 = accountMapper.findById(one);
                if(account1.getMoney().compareTo(money) >= 0){

                    //2.第一个账号减钱
                    Account account2 = new Account();
                    account2.setId(one);
                    account2.setMoney(money.multiply(new BigDecimal(-1)));
                    accountMapper.tranfer(account2);

                    //模拟错误
                    int i = 1/0;

                    //3.第二个账号加钱
                    Account account3 = new Account();
                    account3.setId(two);
                    account3.setMoney(money);
                    accountMapper.tranfer(account3);

                }
            }
        });

        return true;
    }*/

    public boolean tranfer(int one, int two, BigDecimal money) {

                //1.判断钱够不够
                Account account1 = accountMapper.findById(one);
                if(account1.getMoney().compareTo(money) >= 0){

                    //2.第一个账号减钱
                    Account account2 = new Account();
                    account2.setId(one);
                    account2.setMoney(money.multiply(new BigDecimal(-1)));
                    accountMapper.tranfer(account2);

                    //模拟错误
                    int i = 1/0;

                    //3.第二个账号加钱
                    Account account3 = new Account();
                    account3.setId(two);
                    account3.setMoney(money);
                    accountMapper.tranfer(account3);

                    return true;
                }
        return false;
    }
}
